#!/bin/sh
# Created 2010-03-17 by Jimmy Wu
#
# Temporary files:
#  gss.gp  : gnuplot file
#  temp.gss: temporary coordinates
#
# Environment:
#   CLASSPATH	must include gss.FracToDouble

GP=gss.gp
gsstemp=temp.gss

usage() {
    echo Usage: $(basename "$0") "[OPTION]... gssfile [vertices color pointtype]..."
    echo Outputs a svg file using gnuplot
    echo 
    echo '  -w	linewidth'
    #echo '  -p	pointsize'
}

if [ -z "$1" ] ; then
	usage >&2
	exit 1;
fi

# path to gnuplot
Gnuplot=`which gnuplot`

linewidth=.1
#pointsize=.6
[ $( expr "$(basename "$0")" : '.*thick.*' ) -gt 0 ] && linewidth=.5

# process parameters and options
while getopts :w:p: opt ; do
    case "$opt" in 
	w)  linewidth="$OPTARG" ;;
	#p)  pointsize="$OPTARG" ;;
	\?) echo Invalid argument: -$OPTARG >&2; exit 1;;
	:)  echo Option -$OPTARG requires an argument >&2; exit 1;;
    esac
done

shift $(($OPTIND - 1))

inputgss="$1"
shift
gssfile="$inputgss"
output=${gssfile}.svg
fractodouble=gss.FracToDouble
doublefile="$gssfile".double

# convert fractions to decimals if necessary
if grep -q '/' "$gssfile" ; then
    java $fractodouble "$gssfile" "$doublefile"
    gssfile="$doublefile"
fi

# set up file of gnuplot commands ($GP)
: > $GP

echo "gssfile='$gsstemp'" >> $GP
echo "outfile='$output'" >> $GP
cat >> $GP << EOF
#set format ""
set xtics mirror 5 scale .4
set ytics mirror 5 scale .4
set mxtics 5
set mytics 5
unset border
unset key
set terminal svg size 800,800
#set terminal svg dynamic
set output outfile
EOF

plotcmd='plot gssfile using 1:2 with lines linewidth '"$linewidth"' linecolor rgb "black"'

count=1
while [ $# -ge 3 ] ; do
    vertexfile="$1"
    color="$2"
    pointtype="$3"
    pointsize="$4"
    echo "vertexfile${count}='$vertexfile'" >> $GP
    plotcmd="$plotcmd, vertexfile${count} pointtype $pointtype pointsize $pointsize linecolor rgb \"$color\""
    count=$(($count + 1))
    shift 4
done
echo "$plotcmd" >> $GP

# convert 'x1 y1 x2 y2' to 'x1 y1 \nx2 y2'
sed -e 's/\([[:digit:].]* [[:digit:].]*\) \([[:digit:].]* [[:digit:].]*\)/\1\n\2\n/' "$gssfile" > $gsstemp

$Gnuplot $GP

# clean up
#/bin/rm $GP
#/bin/rm $gsstemp

exit
#unset xtics
#unset ytics
